﻿#pragma once
#include <queue>
#include "Common/Utility/Service.h"
#include "base/core/singleton.h"
#include "base/core/os/thread.h"
#include "base/core/os/mutex.h"

#define  g_GetServiceMgr() (ServiceMgr::Instance())

struct SERVICE_MAKER 
{
    MakeService  Make;
    DelService   Del;

    SERVICE_MAKER() 
	{
        Make = NULL;
        Del = NULL;
    }
};

struct LogConfig
{
	std::string logfileIndex;
	uint32_t    maxLine;
	uint16_t priority;
};

struct ConsoleCmd 
{
    char  cmd[256];
    ConsoleCmd(const char* c = NULL);
    ConsoleCmd& operator = (const ConsoleCmd& c);
};

class NetCallbackImp : public ICallback
{
public:
    NetCallbackImp();
    virtual ~NetCallbackImp();
    virtual bool OnRecv(const char* data, int len, ISession* session, uint64_t time_ms) override;
    virtual bool OnConnect(ISession* session, void* req, void* context, bool success) override;
    virtual bool OnAccept(ISession* session, void* req, void* context) override;
    virtual bool OnClose(ISession* session, CloseFlag flag) override;

protected:
    char* m_uncompressBuf;
};

class ServiceMgr : public AutoSingleton<ServiceMgr>
{
    friend class AutoSingleton<ServiceMgr>;

public:
    bool	Init(const char* configFile);
    bool    UnInit();
    bool    Loop();
    bool    SetExitSignal();
protected:
    static void _InputThreadFunction(void *param);

    bool	_HandleConsoleCmd();
    bool    _ProcessCommand(const char* cmd);
    bool    _RegisteServiceMaker();
	bool    _LoadConfig(const char* config, LogConfig& logConf);
    bool    _LoadService(const char* config);
    bool    _AddService(ServiceType type, const char* configFile);
    bool    _DelService(Service* service);
    bool    _TriggerQuit();
	bool    _LogInit(LogConfig& logConf);

protected:
    int                    m_serviceCount;
    uint32_t               m_loopSleep;
    NetInit                m_netInit;
    Net*                   m_net;
    NetCallbackImp         m_netCallback;
    Service*               m_services[SERVICE_COUNT];
    SERVICE_MAKER          m_serviceMaker[SERVICE_COUNT];
    std::queue<ConsoleCmd> m_consoleCmd;
    MutexLock              m_consoleCmdLock;
    Thread                 m_inputThread;    
    bool                   m_ExitFlag;

	list<uint32_t>         m_lstOnlineNum;

protected:
    ServiceMgr();
    virtual ~ServiceMgr()override;
};


